//
//  PayViewModel.m
//  RedWinMall
//
//  Created by HeDianZhao on 2018/8/10.
//  Copyright © 2018年 HeDianZhao. All rights reserved.
//

#import "PayViewModel.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "HGOrderCenterVC.h"

static PayViewModel *_payService = nil;
@implementation PayViewModel

+ (instancetype)sharePayService {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _payService = [[PayViewModel alloc] init];
        
    });
    return _payService;
}

- (instancetype)init {
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySucess:) name:kAliPayScuess object:nil];
    }
    return self;
}

- (void)AliPayWithSignature:(NSString *)signature {
    
    [[AlipaySDK defaultService] payOrder:signature fromScheme:@"hjsc" callback:^(NSDictionary *resultDic) {
        if ([resultDic[@"resultStatus"] integerValue] == 9000) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kAliPayScuess object:nil userInfo:@{@"payNo" : resultDic[@"result"]}];
        } else if ([resultDic[@"resultStatus"] integerValue] == 6001) {
            [[XNProgressHUD shared] showErrorWithTitle:@"用户取消支付"];
        } else if ([resultDic[@"resultStatus"] integerValue] == 4000) {
            [[XNProgressHUD shared] showErrorWithTitle:@"订单支付失败"];
        }
        NSLog(@"reslut = %@",resultDic);
    }];
}


- (void)WeChatWithModel:(PayModel *)model {
    
    if ([WXApi isWXAppInstalled]) {
        [WXApi registerApp:model.appid];
        
        PayReq *request = [[PayReq alloc] init];
        //商家向财付通申请的商家id
        request.partnerId = model.partnerId;
        //预支付订单:绑定了我的商品的基本信息 (后台生成的id)
        request.prepayId= model.prepayId;
        //商家根据财付通文档填写的数据和签名 : 微信的标识 意味着是微信支付 不是别的服务
        request.package = model.packageValue;
        //随机串，防重发
        request.nonceStr= model.nonceStr;
        //时间戳，防重发
        UInt32 timeStamp = [model.timeStamp intValue];
        request.timeStamp = timeStamp;
        //商家根据微信开放平台文档对数据做的签名: 是一种加密方式 所有的支付都需要加密
        request.sign= model.sign;
        [WXApi sendReq:request];
    }else{
        [[XNProgressHUD shared] showErrorWithTitle:@"尚未安装微信"];
    }
}

#pragma mark - 支付成功做的操作
- (void)paySucess:(NSNotification *)dict {
    
    NSString *payNo = @"";
    if ([dict.userInfo[@"pay"] isEqualToString:@"weixin"]) {
        payNo = [[NSUserDefaults standardUserDefaults] objectForKey:@"oderNo"];
    } else {
        payNo = dict.userInfo[@"payNo"];
        NSData *jsonData = [payNo dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        payNo = dic[@"alipay_trade_app_pay_response"][@"out_trade_no"];
    }
    
    NSString *oderNo = [[NSUserDefaults standardUserDefaults] objectForKey:@"oderNo"];
    
    
    
    NSDictionary *parameters = @{
                                 @"orderNo" : oderNo,
                                 @"payNo" : payNo
                                 };
    [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/order/pay/success") parameters:parameters completion:^(LMJBaseResponse *response) {
        if (response.responseModel.status == 1) {
            HGOrderCenterVC *vc = [[HGOrderCenterVC alloc] init];
            vc.type = 2;
            [[Utility currentViewController].navigationController pushViewController:vc animated:YES];
        }
    }];
}

@end

@implementation PayModel

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {}

@end
